package com.mirror.utils.weibo;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.mirror.utils.net.NetHandler;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.webview.OAuthV2AuthorizeWebView;
import com.weibo.sdk.android.Weibo;
import com.weibo.sdk.android.WeiboAuthListener;
import com.weibo.sdk.android.WeiboDialogError;
import com.weibo.sdk.android.WeiboException;

public class OpenPlatform {

	private static final String TAG = "OpenPlatform";

	private Context context;

	/** 新浪微博 */
	private Weibo sina;

	/** 腾讯微博 */
	private OAuthV2 tencent;

	/** 登录监听 */
	private OnLoginListener onLoginListener;

	public OpenPlatform() {
	}

	public OpenPlatform(Context context, OnLoginListener onLoginListener) {
		this.context = context;
		this.onLoginListener = onLoginListener;
	}

	/**
	 * 请求开放平台登录授权
	 */
	public void login(int openType) {
		switch (openType) {
			case OpenConstant.SINA.OPEN_TYPE:
				sinaLogin();
				break;
			case OpenConstant.TENCENT.OPEN_TYPE:
				tencentLogin();
				break;
			default:
				break;
		}
	}

	/**
	 * 新浪微博登录
	 */
	private void sinaLogin() {
		Log.i(TAG, "请求新浪微博开放平台授权");
		sina = Weibo.getInstance(OpenConstant.SINA.APP_ID, OpenConstant.SINA.REDIRECT_URL);
		sina.authorize(context, new WeiboAuthListener() {

			@Override
			public void onComplete(Bundle response) {
				Log.i(TAG, "新浪微博开放平台授权成功：" + response.toString());
				// 清除Cookie缓存
				NetHandler.clearCookie(context);
				onLoginListener.onSinaComplete(new OpenAccount(response.getString(OpenConstant.SINA.UID), OpenConstant.SINA.OPEN_TYPE, response
				        .getString(OpenConstant.SINA.ACCESS_TOKEN), System.currentTimeMillis()));
			}

			@Override
			public void onWeiboException(WeiboException arg0) {
			}

			@Override
			public void onError(WeiboDialogError arg0) {
			}

			@Override
			public void onCancel() {
			}
		});
	}

	/**
	 * 腾讯微博登录 - 操蛋的腾讯
	 */
	private void tencentLogin() {
		Log.i(TAG, "请求腾讯微博开放平台授权");
		tencent = new OAuthV2(OpenConstant.TENCENT.REDIRECT_URL);
		tencent.setClientId(OpenConstant.TENCENT.APP_ID);
		tencent.setClientSecret(OpenConstant.TENCENT.APP_SECRET);

		Intent intent = new Intent(context, OAuthV2AuthorizeWebView.class);
		intent.putExtra(OpenConstant.TENCENT.OAUTH, tencent);

		onLoginListener.onTencentStart(intent);
	}

	/**
	 * 登录回调接口
	 */
	public interface OnLoginListener {

		/**
		 * 新浪登录回调方法
		 */
		void onSinaComplete(OpenAccount openAccount);

		/**
		 * 腾讯登录回调方法
		 */
		void onTencentStart(Intent intent);
	}

	public Weibo getSina() {
		return sina;
	}

	public OAuthV2 getTencent() {
		return tencent;
	}

}
